const http = require("http");
const express = require("express");
const socketIo = require("socket.io");
const app = express();
const httpServer = http.createServer(app);
const io = socketIo(httpServer);
const userList = {};// 将socket.id作为属性的名字，将昵称作为属性的值。
app.use(express.json());
app.use(express.static(__dirname));
io.on("connection",function(socket){
    console.log("连接成功",socket.id);
    // 进入房间
    socket.on("intoRoom",function(nickName){
        console.log("intoRoom",nickName)
        userList[socket.id] = nickName;
        // 推送消息
        io.emit("online",nickName,Object.keys(userList).length)
    });
    socket.on("say",function(context){
        // 推送消息
        io.emit("sayAll",userList[socket.id],context);
    })
    socket.on("disconnect",function(){
        const nikeName = userList[socket.id];
        delete userList[socket.id];
        // 通知聊天室退出房间信息
        io.emit("quitRoom",nikeName);
    })
})
app.post("/login",(req,res)=>{
    const {nickName} = req.body;
    if(Object.values(userList).includes(nickName)){
        res.json({
            ok:-1,
            msg:"您输入的昵称已经存在！"
        })
    }else{
        res.json({
            ok:1,
            msg:"成功"
        })
    }
})
httpServer.listen(80,()=>{
    console.log("success");
})
